
const passportJwt = require('passport-jwt');
const socketIo = require('socket.io');


module.exports = app => {
  console.log('***', app.config.env);

  const { config } = app;
  const JwtStrategy = passportJwt.Strategy;
  const ExtractJwt = passportJwt.ExtractJwt;


  const options = {};
  options.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
  options.secretOrKey = config.authToken.secretKey || 'zG@YLg';
  options.passReqToCallback = true;
  // options.jsonWebTokenOptions = {};

  // 挂载 strategy
  app.passport.use(new JwtStrategy(options, function(req, jwt_payload, done) {
    app.passport.doVerify(req, jwt_payload, done);
  }));

  app.passport.verify(async (ctx, jwt_payload) => {
    // 检查用户
    const existsUser = await app.model.Users.findOne({ where: { id: jwt_payload.uid } });

    if (existsUser) {
      return existsUser;
    }

    return;

  });


  app.sessionStore = {
    async get(key) {
      const res = await app.redis.get(key);
      if (!res) return null;
      return JSON.parse(res);
    },

    async set(key, value, maxAge) {
      // maxAge not present means session cookies
      // we can't exactly know the maxAge and just set an appropriate value like one day
      if (!maxAge) maxAge = 24 * 60 * 60 * 1000;
      value = JSON.stringify(value);
      await app.redis.set(key, value, 'PX', maxAge);
    },

    async destroy(key) {
      await app.redis.del(key);
    },
  };


  // app.on('server', server => {
  //   // console.log('🐯🐯🐯 ~ file: app.js:68 ~ server：', server);

  //   const io = socketIo(server);
  //   io.on('connection', socket => {
  //     console.log('new connection');
  //   });
  // });


  // TODO: 添加该代码会造成，每次查询数据表后出现删除的清况？
  // if (app.config.env === 'local' || app.config.env === 'unittest') {
  //   app.beforeStart(async () => {
  //     await app.model.sync({ force: true });
  //   });
  // }
};
